package com.lb.phonetest.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.lb.phonetest.common.Result;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;

@Service
public class PhoneServiceimpel implements PhoneService {

    private static final String API_URL = "https://cx.shouji.360.cn/phonearea.php?number=%s";

    public Result getPhoneLocation(String phone)  {
        RestTemplate restTemplate = new RestTemplate();
        String url = String.format(API_URL, phone);

        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                String responseBody = response.getBody();

                // 使用 ObjectMapper 解析 JSON 数据
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(responseBody);

                // 提取所需信息
                JsonNode dataNode = rootNode.path("data");
                String province = dataNode.path("province").asText();
                String city = dataNode.path("city").asText();
                String sp = dataNode.path("sp").asText();

                // 将数据封装到 Result 对象中
                Result result = new Result();
                result.setData(Map.of(
                        "province", province,
                        "city", city,
                        "sp", sp
                ));
                return result;
            } else {
                throw new RuntimeException("API request failed with status code: " + response.getStatusCode());
            }
        } catch (Exception e) {
            System.err.println("Failed to fetch phone location: " + e.getMessage());
            return new Result(); // 返回空结果或默认值
        }
    }
}